package com.cl.service;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.springframework.stereotype.Component;

import com.cl.auth.stateless.StatelessUser;
import com.cl.dto.UserDTO;
import com.cl.entity.AccessToken;
import com.cl.entity.UGroup;
import com.cl.entity.UUser;

@Component
public class DTOHelper {

	/**
	 *
	 * @param user
	 * @param group
	 * @param accessToken
	 * @return
	 */
	public UserDTO buildUserDTO(UUser user, UGroup group, AccessToken accessToken){
		UserDTO dto = new UserDTO();
		if (user!=null && user.getUserId()!=null) {
			dto.success = true;
			dto.userId = user.getUserId();
			dto.userName = user.getName();
			dto.orgDn = user.getOrgId();
			dto.orgName = user.getOrgName();
			dto.officeName = user.getOfficeName();
			dto.role = group.getRoleid();
			dto.perms = group.getPerms();
			dto.menu = group.getGrantMenu();
			dto.token = accessToken;
		} else {
			dto.success = false;
		}
		return dto;
	}

	/**
	 *
	 * @param user
	 * @return
	 */
	public UserDTO buildUserDTO(StatelessUser user){
		UserDTO dto = new UserDTO();
		if (user!=null && user.getUserId()!=null) {
			dto.success = true;
			dto.userId = user.getUserId();
			dto.userName = user.getName();
			dto.orgDn = user.getOrgId();
			dto.orgName = user.getOrgName();
			dto.officeName = user.getOfficeName();
			dto.role = user.getUgroup().getRoleid();
			dto.perms = user.getUgroup().getPerms();
			dto.menu = user.getUgroup().getGrantMenu()==null?"":user.getUgroup().getGrantMenu();
		} else {
			dto.success = false;
		}
		return dto;
	}

	/**
	 *
	 * @param user
	 * @param group
	 * @param accessToken
	 * @return
	 */
	public StatelessUser buildStatelessUserDTO(UUser user, UGroup group, AccessToken accessToken){
		StatelessUser statelessUser = new StatelessUser();
		statelessUser.setAccessToken(accessToken.getAccessToken());
		if (user!=null && user.getUserId()!=null) {
			statelessUser.setUserId(user.getUserId());
			statelessUser.setName(user.getName());
			if (group != null && group.getRoleid() != null) {
				statelessUser.setRoles(getListByGroup(group.getRoleid()));
				statelessUser.setGrantMenu(group.getGrantMenu());
				statelessUser.setPermissions(getSetByGroup(group.getPerms()));
			}
		}
		return statelessUser;
	}

	/**
	 *
	 * @param group
	 * @return
	 */
	public List<String> getListByGroup(String group) {
		List<String> list = new ArrayList<String>();
		if (group!=null) {
			String[] items = group.split(",");
			for (String item:items) {
				list.add(item);
			}
		}
		return list;
	}

	/**
	 *
	 * @param group
	 * @return
	 */
	public Set<String> getSetByGroup(String group) {
		Set<String> set = new HashSet<String>();
		if (group!=null) {
			String[] items = group.split(",");
			for (String item:items) {
				set.add(item);
			}
		}
		return set;
	}


}
